import Plugin from './plugin.js';
import { SignState, UploadingState, PauseState, DoneState, ErrorState } from './state.js';

export default class Upload {
    constructor(fileName) {
        this.plugin = new Plugin();
        this.fileName = fileName;
        this.buttonSwitch = null;
        this.buttonDelete = null;
        this.signState = new SignState(this); // 设置初始状态为 waiting
        this.uploadingState = new UploadingState(this);
        this.pauseState = new PauseState(this);
        this.doneState = new DoneState(this);
        this.errorState = new ErrorState(this);
        this.currState = this.signState; // 设置当前状态
    }

    init() {
        this.dom = document.createElement('div');
        this.dom.innerHTML = `
            <span>文件名称：${this.fileName}</span>
            <button data-action="switch">扫描中</button>
            <button data-action="delete">删除</button>`;
        
        document.body.appendChild(this.dom);

        this.buttonSwitch = this.dom.querySelector('[data-action="switch"]');
        this.buttonDelete = this.dom.querySelector('[data-action="delete"]');
        
        this.bindEvent();
        this.sign();
    }

    bindEvent() {
        this.buttonSwitch.onclick = () => {
            this.currState.clickSwitchHanlder();
        }

        this.buttonDelete.onclick = () => {
            this.currState.clickDeleteHanlder();
        }
    }

    sign() {
        this.plugin.sign();
        this.currState = this.signState;
    }

    uploading() {
        this.buttonSwitch.innerHTML = '正在上传，点击暂停';
        this.plugin.uploading();
        this.currState = this.uploadingState;
    }

    pause() {
        this.buttonSwitch.innerHTML = '已暂停，点击继续上传';
        this.plugin.pause();
        this.currState = this.pauseState;
    }

    done() {
        this.buttonSwitch.innerHTML = '上传完成';
        this.plugin.done();
        this.currState = this.doneState;
    }

    error() {
        this.buttonSwitch.innerHTML = '上传失败';
        this.currState = this.errorState;
    }

    del() {
        this.plugin.del();
        this.dom.parentNode.removeChild(this.dom);
    }
}